package com.wing.product.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.config.BaseDataInit;
import com.wing.order.model.response.ScanDeliveryVo;
import com.wing.product.dao.ProductPackLabelDao;
import com.wing.product.model.entity.ProductPackLabel;
import com.wing.product.model.request.ProductPackLabelForm;
import com.wing.product.model.response.ProductPackLabelVO;
import com.wing.web.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.*;

/**
 * 产品包装条码-ServiceImpl
 *
 * @author
 */
@Service
@Slf4j
public class ProductPackLabelServiceImpl extends ServiceImpl<ProductPackLabelDao, ProductPackLabel> implements ProductPackLabelService {

    @Autowired
    private ProductPackLabelDao productPackLabelDao;

    @Override
    public int add(ProductPackLabelForm productPackLabelForm) {

        //校验

        ProductPackLabel productPackLabel =new ProductPackLabel();
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(ProductPackLabel.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(productPackLabelForm, productPackLabel, copyOptions);
        productPackLabel.setId(null);
        int count=baseMapper.insert(productPackLabel);
        productPackLabelForm.setId(productPackLabel.getId());
        return count;
    }

    @Override
    public List<ProductPackLabelVO> list4app(Map<String, Object> params) {
        return baseMapper.list4app(params);
    }

    @Override
    public Page<ProductPackLabelVO> pageList4app(Page page, Map<String, Object> params) {
        List<ProductPackLabelVO> list = baseMapper.list4app(page, params);
        page.setRecords(list);
        return page;
    }

    @Override
    public ProductPackLabelVO get4appById(Long id) {
        return baseMapper.get4appById(id);
    }

    @Override
    public ProductPackLabelVO getProductPackLabelVoList(String code) {
        return productPackLabelDao.getProductPackLabelVOList(code);
    }




    @Override
    @Transactional
    public List<ProductPackLabel> inertPackIndex(ProductPackLabelForm productPackLabelForm) {
            String enterpriseCode=JwtUtils.getEnterpriseCode();
            QueryWrapper<ProductPackLabel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("batch_code", productPackLabelForm.getBatchCode());

            if(productPackLabelForm.getCreator() != null && StringUtils.isNotEmpty(productPackLabelForm.getCreatorName())){
                productPackLabelForm.setCreator(productPackLabelForm.getCreator());
                productPackLabelForm.setCreatorName(productPackLabelForm.getCreatorName());
            }else{
                productPackLabelForm.setCreator(JwtUtils.getLoginUserId());
                productPackLabelForm.setCreatorName(JwtUtils.getLoginUsername());
            }

            Integer codeNumber;
            //添加成功条数
            Integer successNumber = 0;
            Integer mun = 0;
            List<ProductPackLabel> packs = new ArrayList<>();
            // List<ProductPackLabel> newlabels = new ArrayList<>();
            for (int i = 0; i < productPackLabelForm.getAddCount(); i++) {
                 packs= this.list(queryWrapper);
                if (packs.size() > 0) {
//                    if (mun > 0) {
//                        codeNumber = mun + 1;
//                    } else {
                        int dex = packs.get(packs.size() - 1).getCode().lastIndexOf("-")+1;
                        String code = packs.get(packs.size() - 1).getCode().substring(dex);

                        codeNumber = Integer.parseInt(code) + 1;
//                        mun = codeNumber;
//                    }
                    productPackLabelForm.setCode(enterpriseCode+productPackLabelForm.getBatchCode().concat("-" + codeNumber.toString()));
//                this.add(productPackLabelForm);
                  //设置单位包装==换算率
                    /*ProductPack pack = productPackService.getById(productPackLabelForm.getPackId());
                    productPackLabelForm.setBaseRate(pack.getBaseRate());*/
                }
            else {
                    productPackLabelForm.setCode(enterpriseCode+productPackLabelForm.getBatchCode().concat("-".concat(String.valueOf(i + 1))));
                    //设置单位包装==换算率
                   /* ProductPack pack = productPackService.getById(productPackLabelForm.getPackId());
                    productPackLabelForm.setBaseRate(pack.getBaseRate());*/
                }
                productPackLabelForm.setId(null);
                successNumber += this.add(productPackLabelForm);

                /*ProductPackLabel productPackLabel =new ProductPackLabel();
                CopyOptions copyOptions = CopyOptions.create()
                        .setEditable(ProductPackLabel.class)
                        .setIgnoreError(true)
                        .setIgnoreNullValue(true);
                BeanUtil.copyProperties(productPackLabelForm, productPackLabel, copyOptions);
                newlabels.add(productPackLabel);*/
            }
            return packs;
    }

    @Override
    @Transactional
    public List<ProductPackLabel> inertPackIndex2(ProductPackLabelForm productPackLabelForm) {
        String enterpriseCode=JwtUtils.getEnterpriseCode();
        QueryWrapper<ProductPackLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("batch_code", productPackLabelForm.getBatchCode());

        if(productPackLabelForm.getCreator() != null && StringUtils.isNotEmpty(productPackLabelForm.getCreatorName())){
            productPackLabelForm.setCreator(productPackLabelForm.getCreator());
            productPackLabelForm.setCreatorName(productPackLabelForm.getCreatorName());
        }else{
            productPackLabelForm.setCreator(JwtUtils.getLoginUserId());
            productPackLabelForm.setCreatorName(JwtUtils.getLoginUsername());
        }

        Integer codeNumber;
        //添加成功条数
        Integer successNumber = 0;
        Integer mun = 0;
        //换算率
        Integer baseRate = productPackLabelForm.getQuantity();
        //生产入库计划总的送料数
        Integer feedQuantity = productPackLabelForm.getFeedQuantity();
        //需要生产的条数
        Integer addCount = productPackLabelForm.getAddCount();
        //取余
        Integer number = feedQuantity % addCount;
        List<ProductPackLabel> packs=new ArrayList<>();
        for (int i = 0; i < productPackLabelForm.getAddCount(); i++) {
            if((feedQuantity - baseRate) < 0){
                //最后一次
                System.out.println(feedQuantity%baseRate);
                //生产最后一个条码时，将余数赋值给条码数量
                productPackLabelForm.setSurplusQuantity(feedQuantity % baseRate);
                productPackLabelForm.setQuantity(feedQuantity % baseRate);
            }
            feedQuantity = feedQuantity - baseRate;

            packs= this.list(queryWrapper);
            if (packs.size() > 0) {
//                    if (mun > 0) {
//                        codeNumber = mun + 1;
//                    } else {
                int dex = packs.get(packs.size() - 1).getCode().lastIndexOf("-")+1;
                String code = packs.get(packs.size() - 1).getCode().substring(dex);

                codeNumber = Integer.parseInt(code) + 1;
//                        mun = codeNumber;
//                    }
                productPackLabelForm.setCode(enterpriseCode+productPackLabelForm.getBatchCode().concat("-" + codeNumber.toString()));
//                this.add(productPackLabelForm);
            }
            else {
                productPackLabelForm.setCode(enterpriseCode+productPackLabelForm.getBatchCode().concat("-".concat(String.valueOf(i + 1))));
            }

            successNumber += this.add(productPackLabelForm);
        }
        return packs;
    }

    public static void main(String[] args) {

        //换算率
        Integer baseRate = 10;
        //生产入库计划总的送料数
        Integer feedQuantity = 11;
        //需要生产的条数
        Integer addCount = 2;
        for (int i = 0; i < addCount; i++) {
            if((feedQuantity - baseRate) >= 0){
                //正常
                System.out.println(baseRate);
            }else{
                //最后一次
                System.out.println(feedQuantity%baseRate);
            }
            feedQuantity = feedQuantity - baseRate;
        }
    }
    /**
     * 提取标签
     *
     * @return {@link Integer}
     */
    @Override
    @Transactional
    public ProductPackLabelForm extractLabel4InventoryIn(String code, Integer extract,Integer addCount) {
        QueryWrapper<ProductPackLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        ProductPackLabel one = this.getOne(queryWrapper);
        if(Objects.nonNull(one)){
            if (ProductPackLabel.Status.inventoryIn.equals(one.getStatus())){
                throw new BusinessException("此条码已入库");
            }
            ProductPackLabelForm productPackLabelForm =new ProductPackLabelForm();
            BeanUtil.copyProperties(one,productPackLabelForm);
            //新数据剩余数量计算,添加原条码 其余信息一致
            productPackLabelForm.setSurplusQuantity(one.getQuantity()-extract).setQuantity(one.getQuantity()-extract).setQuantity(one.getQuantity()-extract)
                    .setExtractQuantity(one.getQuantity()-extract).setOriginalLabelCode(one.getCode());
            if(Objects.isNull(addCount)){
                productPackLabelForm.setAddCount(1);
            }else{
                productPackLabelForm.setAddCount(addCount);
            }
            if(!extract.equals(one.getQuantity())  ){
                productPackLabelForm.setId(null);
                productPackLabelForm.setStatus(ProductPackLabel.Status.created);
                inertPackIndex(productPackLabelForm);
            }
            one.setQuantity(extract);
            one.setSurplusQuantity(extract);
            one.setExtractQuantity(extract);
            one.setStatus(ProductPackLabel.Status.inventoryIn);
//            one.setStatus(ProductPackLabel.Status.empty);
            this.updateById(one);

            return productPackLabelForm;
        }
        return null;

    }

    @Override
    @Transactional
    public ProductPackLabelForm extractLabel4InventoryIn(String code, Integer extract,Integer addCount,Long boxId,Long warehouseId,Long areaId,Long shelfId,Long spaceId) {
        QueryWrapper<ProductPackLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        ProductPackLabel one = this.getOne(queryWrapper);
        if(Objects.nonNull(one)){
            if (ProductPackLabel.Status.inventoryIn.equals(one.getStatus())){
                throw new BusinessException("此条码已入库");
            }
            ProductPackLabelForm productPackLabelForm =new ProductPackLabelForm();
            BeanUtil.copyProperties(one,productPackLabelForm);
            //新数据剩余数量计算,添加原条码 其余信息一致
            productPackLabelForm.setSurplusQuantity(one.getQuantity()-extract).setQuantity(one.getQuantity()-extract).setQuantity(one.getQuantity()-extract)
                    .setExtractQuantity(one.getQuantity()-extract).setOriginalLabelCode(one.getCode());
            if(Objects.isNull(addCount)){
                productPackLabelForm.setAddCount(1);
            }else{
                productPackLabelForm.setAddCount(addCount);
            }
            if(!extract.equals(one.getQuantity())  ){
                productPackLabelForm.setId(null);
                productPackLabelForm.setStatus(ProductPackLabel.Status.created);
                inertPackIndex(productPackLabelForm);
            }
            one.setQuantity(extract);
            one.setSurplusQuantity(extract);
            one.setExtractQuantity(extract);
            one.setStatus(ProductPackLabel.Status.inventoryIn);
            one.setBoxId(boxId);
            one.setWarehouseId(warehouseId);
            one.setAreaId(areaId);
            one.setShelfId(shelfId);
            one.setSpaceId(spaceId);
//            one.setStatus(ProductPackLabel.Status.empty);
            this.updateById(one);

            return productPackLabelForm;
        }
        return null;

    }


    @Override
    @Transactional
    public ProductPackLabelForm extractLabel4InventoryOut(String code, Integer extract,Integer addCount) {
        QueryWrapper<ProductPackLabel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("code",code);
        ProductPackLabel one = this.getOne(queryWrapper);
        if(Objects.nonNull(one)){
            if (ProductPackLabel.Status.inventoryOut.equals(one.getStatus())){
                throw new BusinessException("此条码已出库");
            }
            ProductPackLabelForm productPackLabelForm =new ProductPackLabelForm();
            BeanUtil.copyProperties(one,productPackLabelForm);
            //新数据剩余数量计算,添加原条码 其余信息一致
            productPackLabelForm.setSurplusQuantity(one.getQuantity()-extract).setQuantity(one.getQuantity()-extract)
                    .setExtractQuantity(one.getQuantity()-extract).setOriginalLabelCode(one.getCode());
            if(Objects.isNull(addCount)){
                productPackLabelForm.setAddCount(1);
            }else{
                productPackLabelForm.setAddCount(addCount);
            }
            if(!extract.equals(one.getQuantity())  ){
                productPackLabelForm.setId(null);
                inertPackIndex(productPackLabelForm);
            }
              one.setQuantity(extract);
              one.setSurplusQuantity(extract);
              one.setExtractQuantity(extract);
              one.setStatus(ProductPackLabel.Status.inventoryOut);
              one.setBoxId(null);
              one.setWarehouseId(null);
              one.setAreaId(null);
              one.setShelfId(null);
              one.setSpaceId(null);

//            one.setSurplusQuantity(0);
//            one.setExtractQuantity(extract);
//            one.setStatus(ProductPackLabel.Status.empty);
            this.updateById(one);

            return productPackLabelForm;
        }
        throw new BusinessException("未找到条码数据");

    }

    @Override
    public IPage<ProductPackLabelVO> getInventoryPackLabelPageList(Integer page, Integer limit, Long planId) {
        IPage<ProductPackLabelVO> iPage = new Page<ProductPackLabelVO>(page, limit);
        QueryWrapper<ProductPackLabelVO> wrapper = new QueryWrapper<>();
        wrapper.eq("lab.plan_id", planId);
        wrapper.orderByDesc("lab.create_time");
        baseMapper.getInventoryPackLabelPageList(iPage,wrapper);
        return iPage;
    }

    @Override
    public ProductPackLabelVO getPackLabelVOByCode(Long planId, String code,Long warehouseId) {
        return baseMapper.getPackLabelVOByCode(planId,code,warehouseId);
    }

    @Override
    public JsonResult<ProductPackLabelVO> getLabelByCode(String code) {
        ProductPackLabelVO productPackLabelVO=baseMapper.getByCode(code,null);
        if (productPackLabelVO==null){
            return JsonResult.fail("未找到包装条码数据");
        }else{
            return JsonResult.success(productPackLabelVO);
        }
    }
    @Override
    @Transactional
    public JsonResult saveSign(ScanDeliveryVo scanDeliveryVo){
        ProductPackLabel productPackLabel = new ProductPackLabel();
//        productPackLabel.setId(scanDeliveryVo.getId());
        productPackLabel.setSurplusQuantity(scanDeliveryVo.getRealReceive());
        productPackLabel.setQuantity(scanDeliveryVo.getRealReceive());
        productPackLabel.setSkuCode(scanDeliveryVo.getSkuCode());
        productPackLabel.setBarcode(scanDeliveryVo.getPackLabelCode());
        productPackLabel.setCode(scanDeliveryVo.getPackLabelCode());
        productPackLabel.setQuantity(scanDeliveryVo.getRealReceive());
        productPackLabel.setSurplusQuantity(scanDeliveryVo.getRealReceive());
        productPackLabel.setBatchCode(scanDeliveryVo.getBatchCode());
        //查询是否存在
        baseMapper.insert(productPackLabel);
        return JsonResult.success();
    }

    @Override
    public JsonResult<List<ProductPackLabel>> getByPurchaseId(Long purchaseId, String skuCode) {
        QueryWrapper<ProductPackLabel>queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("purchase_id",purchaseId);
        queryWrapper.eq("sku_code",skuCode);
        List<ProductPackLabel> labelList = this.list(queryWrapper);
        return JsonResult.success(labelList);
    }


}
